#include "MyDb.h"

#include "sqlite/CppSQLite3.h"

CMyDb::CMyDb(void)
{
}

CMyDb::~CMyDb(void)
{
}

#define DB_FILE "/tmp/mysvr/db"
void CMyDb::Init()
{
	strncpy(m_szDbFile, DB_FILE, strlen(DB_FILE));
	try
	{
		CppSQLite3DB db;
		db.open(m_szDbFile);
		if (!db.tableExists("user"))
		{
			db.execDML("create table user(id int, name char(20), pwd char(32), host char(20), port char(6), fd int);");
		}
	}
	catch (CppSQLite3Exception& e)
	{
		fprintf(stderr, "%d : %s\n",e.errorCode(), e.errorMessage());
	//	cerr << e.errorCode() << ":" << e.errorMessage() << endl;
	}
}


void CMyDb::Add(int nfd, char *szHost, char *szPort)
{
	char sql[256] = {0};
	sprintf(sql, "select * from user where nfd=%d and szHost=%s and szPort=%s", nfd, szHost, szPort);
	try
	{
		CppSQLite3DB db;
		db.open(m_szDbFile);

		CppSQLite3Buffer sql;
		sql.format("select * from user where nfd=%d and szHost=%s and szPort=%s", nfd, szHost, szPort);
		int ret = db.execDML(sql);
		if (ret > 0)
		{
	//		sprintf(sql, "update table user set n")
		}
		else
		{
			sql.clear();
			sql.format("insert into user (id, host, port, fd) values(COUNT(*)+1, %s, %s, %d);", szHost, szPort, nfd);
			db.execDML(sql);
		}
	}
	catch (CppSQLite3Exception& e)
	{
		fprintf(stderr, "%d : %s\n",e.errorCode(), e.errorMessage());
	}

	return 1;
}